package com.mjh.utils;

import com.mjh.constant.AuthConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class TokenManager {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * token续期
     * @param rememberMe 是否记住我
     * @param token token
     */
    @Async// 异步执行
    public void flushTokenTime(Boolean rememberMe, String token) {
        // 获取token有效时长
        Long expireIn = stringRedisTemplate.getExpire(AuthConstants.TOKEN_REDIS_KEY_PREFIX + token);
        // 判断是否记住我
        if (rememberMe) {
            // 用户选择“记住我”，token有效时长重新刷新为7天
            // 判断token有效时长是否超过阈值
            if (expireIn < AuthConstants.REMEMBER_ME_TOKEN_THRESHOLD_TIME) {
                stringRedisTemplate.expire(AuthConstants.TOKEN_REDIS_KEY_PREFIX + token, Duration.ofSeconds(AuthConstants.REMEMBER_ME_TOKEN_TIME));
            }
        } else {
            // 用户未选择“记住我”，token有效时长重新刷新
            // 判断token有效时长是否超过阈值
            if (expireIn < AuthConstants.TOKEN_EXPIRE_TIME) {
                stringRedisTemplate.expire(AuthConstants.TOKEN_REDIS_KEY_PREFIX + token, Duration.ofSeconds(AuthConstants.TOKEN_TIME));
            }
        }
    }

}
